// deal with  pictures.Handling images, such as compression
package imageDealWith

import (
	"fmt"
	"github.com/nfnt/resize"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io"
	"math/rand"
	"strings"
	"time"
)

func Image(ty string,width uint,reader io.Reader,writer io.Writer) error {
	typeValue := ty[len(ty)-3:]
	typeValue = strings.ToLower(typeValue)
	if typeValue == "png" || typeValue == "jpeg" || typeValue == "jpg"||typeValue =="peg"|| typeValue == "gif" {
	 return Compression(typeValue,width,reader,writer)
	}
	fmt.Errorf("你的格式不对")
} 
//compression pictures. typeValue such as "png" "jpeg" "jpg" "gif".
func Compression(typeValue string, width uint, reader io.Reader, writer io.Writer) error {
	typ := strings.ToUpper(typeValue)
	switch typ {
	case "JPG", "JPEG","PEG":
		jpegdealWithImage(width, reader, writer)
	case "PNG":
		pngdealWithImage(width, reader,writer)
	case "GIF":
		gifdealWithImage(width, reader,writer)
	default:
		return fmt.Errorf("您输入的类型不正确，仅支持png jpg jpeg gif类型")
	}
	return nil
}
func jpegdealWithImage(width uint, arg io.Reader, writer io.Writer) error {
	img, err := jpeg.Decode(arg)
	if err != nil {
		return err
	}
	img1 := resize.Resize(width, 0, img, resize.Lanczos3)
	jpeg.Encode(writer, img1, nil)
	return nil

}

func pngdealWithImage(width uint, arg io.Reader,writer io.Writer) error {
	img, err := png.Decode(arg)
	if err != nil {
		return err
	}
	img1 := resize.Resize(width, 0, img, resize.Lanczos3)
	png.Encode(writer, img1)
	return nil

}

func gifdealWithImage(width uint, arg io.Reader,writer io.Writer) error {
	img, err := gif.Decode(arg)
	if err != nil {
		return err
	}
	img1 := resize.Resize(width, 0, img, resize.Lanczos3)
	gif.Encode(writer, img1, nil)
	return nil

}
